package com.tx.websocket.demo.interceptor;

import com.tx.websocket.demo.model.BaseResource;
import com.tx.websocket.demo.model.User;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Configuration
public class MenuInterceptor implements HandlerInterceptor {

    //后置拦截器，加入菜单
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

        // ajax 请求不返回菜单
        if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
            return;
        }

        User user = (User) SecurityUtils.getSubject().getPrincipal();

        List<BaseResource> resources = user.getResources();

        if(CollectionUtils.isNotEmpty(resources))
            modelAndView.addObject("resources", resources);

        modelAndView.addObject("permMarks", user.getPermMarks());
        modelAndView.addObject("currentUser", user);
    }
}